package cn.edu.pku.cs08.liudun.picventure.view;

import cn.edu.pku.cs08.liudun.picventure.AppConfig;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class GestureView extends View {
	private static final String TAG = "GestureView";
	public GestureView(Context context) {
		super(context);
		init();
	}

	public GestureView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	
	public GestureView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}
	
	Canvas mCanvas = null;
	Paint mPaint = null;
	Paint mResetPaint = null;
	Path mPath = null;
	Bitmap mBmp = null;
	
	float lastX, lastY;
	
	private void init() {
		this.setLongClickable(true);
		mCanvas = new Canvas();
		mPath = new Path();
		mPaint = new Paint();		
		mPaint.setColor(Color.GRAY);
		mPaint.setAlpha(80);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeWidth(AppConfig.PAINT_GESTURE_WIDTH);

		resetBmp();
	}
	
	private void resetBmp() {
		if(mBmp != null) {
			mBmp.recycle();
		}
		int orientation = this.getResources().getConfiguration().orientation;
		switch(orientation) {
		case Configuration.ORIENTATION_PORTRAIT:
			mBmp = Bitmap.createBitmap(this.getResources().getDisplayMetrics().widthPixels, 
					this.getResources().getDisplayMetrics().heightPixels, 
					Bitmap.Config.ARGB_8888);
			break;
		case Configuration.ORIENTATION_LANDSCAPE:
			mBmp = Bitmap.createBitmap(this.getResources().getDisplayMetrics().heightPixels, 
					this.getResources().getDisplayMetrics().widthPixels, 
					Bitmap.Config.ARGB_8888);
			break;
		default:
			mBmp = Bitmap.createBitmap(this.getResources().getDisplayMetrics().widthPixels, 
					this.getResources().getDisplayMetrics().heightPixels, 
					Bitmap.Config.ARGB_8888);
		}
		mCanvas.setBitmap(mBmp);	
	}
	
	@Override
	public void onDraw(Canvas canvas) {
		canvas.drawBitmap(mBmp, 0, 0, null);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float tmpX = event.getX();
		float tmpY = event.getY();		
		switch(event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mPath.reset();
			mPath.moveTo(tmpX, tmpY);
			lastX = tmpX;
			lastY = tmpY;
			
			mCanvas.drawPath(mPath, mPaint);
			break;
		case MotionEvent.ACTION_MOVE:
            mPath.quadTo(lastX, lastY, tmpX, tmpY);
            lastX = tmpX;
			lastY = tmpY;
            
			mCanvas.drawPath(mPath, mPaint);
			this.invalidate();
			break;
		case MotionEvent.ACTION_UP:
			resetBmp();
			this.invalidate();
			mPath.reset();
			break;
		default:
			Log.e(TAG, "event.getAction unknown");
		}
		return true;
	}
}
